package com.bawei.module_home.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.library_common.route.ARouterFragmentPath
import com.bawei.library_mvi.ui.BaseMviLazyFragment
import com.bawei.module_home.R
import com.bawei.module_home.databinding.HomeFragmentHomeBinding
import com.bawei.module_home.intent.SimpleTypeIntent
import com.bawei.module_home.model.entity.SimpleTypeEntity
import com.bawei.module_home.state.SimpleTypeState
import com.bawei.module_home.viewmodel.SimpleTypeViewModel
import com.ivideo.home.widget.XiGuaTitleBar
import kotlinx.coroutines.launch

@Route(path = ARouterFragmentPath.PAGER_HOME)
class HomeFragment : BaseMviLazyFragment<HomeFragmentHomeBinding>() {
    private lateinit var viewModel:SimpleTypeViewModel

    override fun initView() {
        super.initView()
        val list: MutableList<String> = mutableListOf()
        list.add("视频资讯1")
        list.add("视频资讯2")
        list.add("视频资讯3")
        viewDataBinding.xgtbHomeTitlebar.setDataSource(list)

    }

    override fun initEvent() {
        super.initEvent()
        viewDataBinding.xgtbHomeTitlebar.setOnClickCallback(object : XiGuaTitleBar.TitleBarClickCallback {
            override fun onClick(index: Int) {
                showMsg("$index")
            }
        })
    }
    /**
     * 根据状态具体更新UI
     */
    override fun handleState() {
        lifecycleScope.launch {
            viewModel.state.collect{
                when(it){
                    is SimpleTypeState.SimpleTypes ->{
                        showMsg("请求成功 ${it.list.size}")
                        generateTabs(it)
                    }
                    is SimpleTypeState.Error ->{
                        showMsg("请求失败 ${it.exception.message}")
                    }
                    is SimpleTypeState.Empty ->{
                        showMsg("请求空")
                    }
                    is SimpleTypeState.Init ->{
                        showMsg("初始状态")
                    }

                }
            }
        }

    }
    //请求成功加载fragment
    private fun generateTabs(it: SimpleTypeState.SimpleTypes) {
        val homePagerAdapter = HomePagerAdapter(it.list,
            childFragmentManager,
            FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
        viewDataBinding.vpHome.adapter = homePagerAdapter
        viewDataBinding.tlHomeVideotype.setupWithViewPager(viewDataBinding.vpHome)


    }



    class HomePagerAdapter(val types:List<SimpleTypeEntity>, val mFragmentManager:FragmentManager,val mBehavior:Int):FragmentStatePagerAdapter(mFragmentManager,mBehavior){
        private val fragments:MutableList<Fragment> = mutableListOf()

        init {
            types.forEach {
                val simpleTypeFragment = SimpleTypeFragment()
                //为每个fragment设置channelid
                //？？？？为什么这么设计 为了区分不同的fragment，每个fragment都调用SimpleTypeFragment，但是每个frgment数据Ui展示不同
                val bundle= Bundle()
                bundle.putString("channelid",it.channelid)
                simpleTypeFragment.arguments=bundle

                fragments.add(simpleTypeFragment)
            }
        }


        override fun getCount(): Int {
            return fragments.size
        }

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }
        //返回每个tab的标题
        override fun getPageTitle(position: Int): CharSequence? {
            return types[position].typename
        }

    }










    /**
     * 111。发起网络请求：发送意图
     */
    override fun initData() {
        super.initData()
        lifecycleScope.launch{
            viewModel.intents.send(SimpleTypeIntent.getSimpleType)
        }
    }


    override fun getLayout(): Int {
        return R.layout.home_fragment_home
    }





    //viewmodel
    override fun generateViewModel() {
        viewModel = ViewModelProvider(this).get(SimpleTypeViewModel::class.java)
    }


}